import { createApp } from "vue";
import Antd from "ant-design-vue";
import "ant-design-vue/dist/antd.css";
import App from "./App.vue";
// @ts-ignore
import microApp from "@micro-zoe/micro-app";

import router from "./router";

const localEnv = import.meta.env;
const { VITE_ceshi2Host, VITE_viteHost, MODE } = localEnv;

// customElements.define("micro-app", microApp.shadowDOM);
microApp.start({
  lifeCycles: {
    created() {
      console.log("created 全局监听");
    },
    beforemount() {
      console.log("beforemount 全局监听");
    },
    mounted() {
      console.log("mounted 全局监听");
    },
    unmount() {
      console.log("unmount 全局监听");
    },
    error() {
      console.log("error 全局监听");
    },
  },
  plugins: {
    modules: {
      vite: [
        {
          loader(code) {
            if (process.env.NODE_ENV === "development") {
              code = code.replace(
                /(from|import)(\s*['"])(\/vite\/)/g,
                (all) => {
                  return all.replace("/vite/", VITE_viteHost);
                }
              );
            }
            return code;
          },
        },
      ],
      ceshi2: [
        {
          loader(code) {
            if (process.env.NODE_ENV === "development") {
              code = code.replace(
                /(from|import)(\s*['"])(\/ceshi2\/)/g,
                (all) => {
                  return all.replace("/ceshi2/", VITE_ceshi2Host);
                }
              );
            }
            return code;
          },
        },
      ],
    },
  },
  /**
   * 自定义fetch
   * @param url 静态资源地址
   * @param options fetch请求配置项
   * @returns Promise<string>
   */
  fetch(url, options, appName) {
    if (url === "http://localhost:3001/error.js") {
      return Promise.resolve("");
    }

    let config = null;
    if (url === "http://localhost:3001/micro-app/react16/") {
      config = {
        headers: {
          "custom-head": "custom-head",
        },
      };
    }

    return fetch(url, Object.assign(options, config)).then((res) => {
      return res.text();
    });
  },
});

const app = createApp(App);
window.localStorage.setItem("ceshi", "fasdf");
app.use(router).use(Antd).mount("#app");
